package com.ruoyi.supplier.manager;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.ruoyi.supplier.domain.bo.CategoriesBo;
import com.ruoyi.supplier.domain.bo.CategoryAttrBo;
import com.ruoyi.supplier.domain.vo.CategoriesVo;
import com.ruoyi.supplier.domain.vo.CategoryAttrVo;
import com.ruoyi.supplier.domain.vo.cate.AttrVo;
import com.ruoyi.supplier.domain.vo.cate.CateVo;
import com.ruoyi.supplier.service.ICategoriesService;
import com.ruoyi.supplier.service.ICategoryAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CategoryManager {

    @Autowired
    private ICategoriesService iCategoriesService;

    @Autowired
    private ICategoryAttrService categoryAttrService;

    public List<CateVo> getAllTree() {
        CategoriesBo categoriesBo = new CategoriesBo();
        List<CategoriesVo> prev = iCategoriesService.queryList(categoriesBo);
        List<CateVo> list = prev.stream().map(this::getByCategoriesVo).collect(Collectors.toList());
        return getPrev(list,0L);
    }

    private CateVo getByCategoriesVo(CategoriesVo v) {
        CateVo cateVo = new CateVo();
        cateVo.setCategoryId(v.getId());
        cateVo.setImageId(Long.valueOf(v.getImage()));
        cateVo.setName(v.getName());
        cateVo.setImagePath(v.getPath());
        cateVo.setSort(v.getSort());
        cateVo.setParentId(v.getPid());
        List<AttrVo> attrVos = getAttrVoList(v.getId());
        cateVo.setAttrs(attrVos);
        return cateVo;
    }

    private List<AttrVo> getAttrVoList(Long id) {
        CategoryAttrBo attrBo = new CategoryAttrBo();
        attrBo.setCategoryId(id);
        List<CategoryAttrVo> categoryAttrVos = categoryAttrService.queryList(attrBo);
        return categoryAttrVos.stream().map(c -> Convert.convert(AttrVo.class, c)).collect(Collectors.toList());
    }

    private  List<CateVo> getPrev(List<CateVo> list,Long pid){
        List<CateVo> level1 = list.stream().filter(c -> Objects.equals(c.getParentId(), pid)).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(level1)){
            level1.forEach(cateVo -> cateVo.setChildren(getPrev(list,cateVo.getCategoryId())));
        }
        return level1;
    }
}
